package com.example.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dao.Auth;
import com.example.dao.User;
import com.example.dao.UserRole;
import com.example.dao.mapper.UserMapper;

import com.example.dao.mapper.UserRoleMapper;
import com.example.util.JwtUtil;
import com.example.util.TotpUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Slf4j
@Service
@Transactional
public class UserService {
    @Autowired
    private UserMapper userMapper;
    //    private RoleRepo roleRepo;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private TotpUtil totpUtil;
    @Autowired
    private UserRoleMapper userRoleMapper;


    /**
     * 新建一个新用户
     *
     * @param user 用户实体
     * @return 保存后的对象
     */
    public int insertUser(User user) {
        return userMapper.insert(user);
    }

    /**
     * 注册一个新用户
     *
     * @param user 用户实体
     * @return 保存后的对象
     */
    @Transactional
    public int registerUser(User user) {
        int result = 0;
        result = userMapper.insert(user);
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(1l);
        result += userRoleMapper.insert(userRole);
        return result;
    }

    /**
     * 根据用户名密码查找用户
     *
     * @param username
     * @param password
     * @return
     */
    public User findByUsernameAndPassword(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        User result = userMapper.selectOne(queryWrapper);
        if (result != null) {
            if (passwordEncoder.matches(password, result.getPassword())) {
                return result;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 根据相关条件分页查询用户
     *
     * @param user
     * @return
     */
    public List<User> findUsersByPage(User user) {
        return userMapper.findUsersByPage(user);
    }

    /**
     * 根据相关条件查询总数
     *
     * @param user
     * @return
     */
    public int findCount(User user) {
        return userMapper.findCount(user);
    }

    /**
     * 删除用户
     *
     * @param ids
     * @return
     */
    public int deleteUserByIds(Long[] ids) {
        List<Long> list = Arrays.asList(ids);
        return userMapper.deleteBatchIds(list);
    }
    /*public Auth login(UserDetails userDetails) {
        return new Auth(jwtUtil.createAccessToken(userDetails), jwtUtil.createRefreshToken(userDetails));
    }*/

    /*public Auth refreshToken(String accessToken, String refreshToken) {
        if (!jwtUtil.validateRefreshToken(refreshToken) && !jwtUtil.validateWithoutExpiration(accessToken)) {
            throw new BadCredentialProblem();
        }
        return new Auth(jwtUtil.buildAccessTokenWithRefreshToken(refreshToken), refreshToken);
    }*/

    /**
     * 更新用户
     *
     * @param user
     * @return
     */
    public int updateUser(User user) {
        return userMapper.updateById(user);
    }

/*    public Auth loginWithTotp(User user) {
        val toSave = user.withMfaKey(totpUtil.encodeKeyToString());
        val saved = saveUser(toSave);
        return login(saved);
    }*/

/*    public Optional<String> createTotp(User user) {
        return totpUtil.createTotp(user.getMfaKey());
    }*/

/*    public void upgradePasswordEncodingIfNeeded(User user, String rawPassword) {
        if (passwordEncoder.upgradeEncoding(user.getPassword())) {
            userRepo.save(user.withPassword(passwordEncoder.encode(rawPassword)));
        }
    }*/

    /*
     */
/**
 * 取得全部用户列表
 *
 * @return 全部用户列表
 *//*

    public Page<User> findAll(Pageable pageable) {
        return userRepo.findAll(pageable);
    }
*/

    /**
     * 在编辑用户的场景下，判断用户账号是否重复，需要规避用户本身的用户账号
     * 检查用户账号是否存在
     *
     * @param username 用户名
     * @return 存在与否
     */
    public boolean isUsernameExisted(String username, Long id) {
        Map<String, Object> param = new HashMap<>();
        param.put("username", username);
        param.put("id", id);
        return userMapper.findCountByUsername(param) > 0;
    }

    /**
     * 在编辑用户的场景下，判断电邮地址是否重复，需要规避用户本身的电邮地址
     * 检查邮箱是否存在
     *
     * @param email 电邮地址
     * @return 存在与否
     */
    public boolean isEmailExisted(String email, Long id) {
        Map<String, Object> param = new HashMap<>();
        param.put("email", email);
        param.put("id", id);
        return userMapper.findCountByEmail(param) > 0;
    }


    /**
     * 在编辑用户的场景下，判断手机号是否重复，需要规避用户本身的手机号
     * 检查手机号是否存在
     *
     * @param mobile 手机号
     * @return 存在与否
     */
    public boolean isMobileExisted(String mobile, Long id) {
        Map<String, Object> param = new HashMap<>();
        param.put("mobile", mobile);
        param.put("id", id);
        return userMapper.findCountByMobile(param) > 0;
    }
}



